package com.forlove.app.qselect.friend.adapter;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.forlove.app.R;
import com.forlove.app.common.base.ui.BaseActivity;
import com.forlove.app.common.network.ICallBack;
import com.forlove.app.common.network.OkhttpManager;
import com.forlove.app.common.utils.LogUtil;
import com.forlove.app.common.utils.ParseHelper;
import com.forlove.app.common.utils.StringUtils;
import com.forlove.app.common.widget.CircleImageView;
import com.forlove.app.manager.FriendManager;
import com.forlove.app.manager.ServerManager;
import com.forlove.app.manager.UserManager;
import com.forlove.app.qselect.answer.entity.InviteShortLinkEntity;
import com.forlove.app.qselect.answer.widght.InviteFriendDialog;
import com.forlove.app.qselect.friend.entity.MineFriendEntity;
import com.forlove.app.qselect.friend.entity.SearchFriendEntity;
import com.forlove.app.qselect.friend.presenter.AddContactsFriendPresenter;
import com.forlove.app.qselect.friend.ui.SearchUserInfoActivity;
import com.forlove.app.qselect.friend.widget.contact.ChineseToEnglish;
import com.forlove.app.qselect.index.ui.MineInfoActivity;
import com.forlove.app.qselect.login.entity.UserEntity;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 好友分组的adapter
 * Created by yjl on 2017/10/14.
 */

public class AddPhoneFriendAdapter extends BaseExpandableListAdapter {
    private ArrayList<String> groupList = new ArrayList<>();
    private Context mContext;
    private ArrayList<MineFriendEntity> friendEntities = new ArrayList<>();
    private AddContactsFriendPresenter addContactsFriendPresenter;
    private List<List<MineFriendEntity>> childFriendEntity = new ArrayList<>();
    private String from;
    private UserEntity userEntity;
    private String commonShareUrl;
    private String shareUrl;
    private InviteFriendDialog inviteFriendDialog;

    public AddPhoneFriendAdapter(Context context, AddContactsFriendPresenter presenter,
                                 List<MineFriendEntity> friendEntities) {
        this.mContext = context;
        this.friendEntities.clear();
        this.friendEntities.addAll(friendEntities);
        groupList.clear();
        groupList.addAll(initGroup());
        initChildFriend();
        this.addContactsFriendPresenter = presenter;
        userEntity = UserManager.getUesrInfo(mContext);
        commonShareUrl = ServerManager.getServerUrl() + "/invtepage?username=" + URLEncoder.encode(userEntity.userName);
    }

    public void updateFriendList(List<MineFriendEntity> friendEntities) {
        this.friendEntities.clear();
        this.friendEntities.addAll(friendEntities);
        groupList.clear();
        groupList.addAll(initGroup());
        initChildFriend();
    }

    @Override
    public int getGroupCount() {
        return groupList.size();
    }

    @Override
    public int getChildrenCount(int groupPosition) {

        return childFriendEntity.get(groupPosition).size();
    }

    @Override
    public String getGroup(int groupPosition) {
        return groupList.get(groupPosition);
    }

    @Override
    public MineFriendEntity getChild(int groupPosition, int childPosition) {
        return childFriendEntity.get(groupPosition).get(childPosition);
    }

    @Override
    public long getGroupId(int groupPosition) {

        return groupPosition;
    }

    @Override
    public long getChildId(int groupPosition, int childPosition) {
        String title = getGroup(groupPosition);
        MineFriendEntity friendEntity = friendEntities.get(childPosition);
        if (title.equalsIgnoreCase(friendEntity.username_fc)) {
            return childPosition;
        }
        return 0;
    }


    @Override
    public boolean hasStableIds() {
        return false;
    }

    @Override
    public View getGroupView(int groupPosition, boolean isExpanded, View
            convertView, ViewGroup parent) {
        FriendGoupViewHolder friendGoupViewHolder;
        if (convertView == null) {
            LayoutInflater inflater =
                    (LayoutInflater) mContext.getSystemService(
                            Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.item_friend_group, null);
            friendGoupViewHolder = new FriendGoupViewHolder();
            friendGoupViewHolder.goup = (TextView) convertView.findViewById(R.id.text_friend_group);
            convertView.setTag(friendGoupViewHolder);
        } else {
            friendGoupViewHolder = (FriendGoupViewHolder) convertView.getTag();
        }
        if (friendGoupViewHolder != null) {
            friendGoupViewHolder.goup.setText(groupList.get(groupPosition));

        }
        return convertView;
    }

    @Override
    public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View
            convertView, ViewGroup parent) {

        FriendViewHolder friendViewHolder;
        if (convertView == null) {
            LayoutInflater inflater =
                    (LayoutInflater) mContext.getSystemService(
                            Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.item_friends_phone, null);
            friendViewHolder = new FriendViewHolder();
            friendViewHolder.nickeName = (TextView) convertView.findViewById(R.id.text_friend__name);
            friendViewHolder.friendFrom = (TextView) convertView.findViewById(R.id.text_friend_from);
            friendViewHolder.friendName = (TextView) convertView.findViewById(R.id.text_qyq_name);
            friendViewHolder.friendImage = (CircleImageView) convertView.findViewById(R.id.view_friend_photo);
            friendViewHolder.text_friend_states = (TextView) convertView.findViewById(R.id.text_friend_states);
            friendViewHolder.view_friend_phone = convertView.findViewById(R.id.view_friend_phone);
            convertView.setTag(friendViewHolder);
        } else {
            friendViewHolder = (FriendViewHolder) convertView.getTag();
        }
        if (friendViewHolder != null) {
            final MineFriendEntity friendEntity = getChild(groupPosition, childPosition);

            if (StringUtils.isNotEmpty(friendEntity.contactsName)) {
                friendViewHolder.nickeName.setText(friendEntity.contactsName);
            } else if (StringUtils.isNotEmpty(friendEntity.realname)) {
                friendViewHolder.nickeName.setText(friendEntity.realname);
            } else {
                friendViewHolder.nickeName.setText(friendEntity.mobile);
            }
            addContactsFriendPresenter.loadImageView(mContext, friendViewHolder.friendImage, friendEntity.img, R.mipmap.image_mine_friend_avatar);
            if (StringUtils.isNotEmpty(friendEntity.realname)) {
                friendViewHolder.friendFrom.setVisibility(View.VISIBLE);
                friendViewHolder.friendName.setText(friendEntity.realname);
            } else {
                friendViewHolder.friendFrom.setVisibility(View.GONE);
                friendViewHolder.friendName.setText(friendEntity.contactsNumber);
            }
            if (friendEntity.isfriend && !TextUtils.isEmpty(friendEntity.realname)) {
                //是好友，并注册
//                friendViewHolder.text_friend_states.setBackgroundColor(Color.parseColor("#ffffff"));
                friendViewHolder.text_friend_states.setBackground(mContext.getResources().getDrawable(R.drawable.bg_white_corner));
                friendViewHolder.text_friend_states.setTextColor(mContext.getResources().getColor(R.color.str_color_gray));
                friendViewHolder.text_friend_states.setText("已添加");
                friendViewHolder.text_friend_states.setOnClickListener(null);
                //TODO 跳转好友详情页

                friendViewHolder.view_friend_phone.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(mContext, MineInfoActivity.class);
                        Bundle bundle = new Bundle();
                        bundle.putString("mobile", friendEntity.mobile);
                        intent.putExtras(bundle);
                        mContext.startActivity(intent);
                    }
                });
            } else if (!friendEntity.isfriend && !TextUtils.isEmpty(friendEntity.realname)) {
                // 不是好友，但是是注册用户
                friendViewHolder.text_friend_states.setBackground(mContext.getResources().getDrawable(R.drawable.bt_invite_selector));
                friendViewHolder.text_friend_states.setTextColor(mContext.getResources().getColor(R.color.white));
                friendViewHolder.text_friend_states.setText("添加");
                friendViewHolder.view_friend_phone.setOnClickListener(null);
                friendViewHolder.text_friend_states.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //跳转申请加好友界面
                        SearchFriendEntity searchFriendEntity = new SearchFriendEntity();
                        searchFriendEntity.friendEntity = friendEntity;
                        //TODO
                        searchFriendEntity.note_times = friendEntity.charm;
                        Intent intent = new Intent(mContext, SearchUserInfoActivity.class);
                        Bundle bundle = new Bundle();
                        bundle.putSerializable("friendinfo", searchFriendEntity);
                        bundle.putString("mobile", friendEntity.getAvaliableMobile());
                        intent.putExtras(bundle);
                        mContext.startActivity(intent);
                    }
                });
                friendViewHolder.view_friend_phone.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //跳转申请加好友界面
                        SearchFriendEntity searchFriendEntity = new SearchFriendEntity();
                        searchFriendEntity.friendEntity = friendEntity;
                        //TODO
                        searchFriendEntity.note_times = friendEntity.charm;
                        Intent intent = new Intent(mContext, SearchUserInfoActivity.class);
                        Bundle bundle = new Bundle();
                        bundle.putSerializable("friendinfo", searchFriendEntity);
                        bundle.putString("mobile", friendEntity.getAvaliableMobile());
                        intent.putExtras(bundle);
                        mContext.startActivity(intent);
                    }
                });
            } else if (!friendEntity.isfriend && TextUtils.isEmpty(friendEntity.realname)) {
                //不是好友并且未注册
                friendViewHolder.text_friend_states.setBackground(mContext.getResources().getDrawable(R.drawable.bt_invite_selector));
                friendViewHolder.text_friend_states.setTextColor(mContext.getResources().getColor(R.color.white));
                friendViewHolder.text_friend_states.setText("邀请");
                friendViewHolder.view_friend_phone.setOnClickListener(null);
                friendViewHolder.text_friend_states.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        shareUrl = commonShareUrl;
                        if (!TextUtils.isEmpty(friendEntity.getAvaliableName())) {
                            shareUrl = commonShareUrl + "&invt=" + URLEncoder.encode(friendEntity.getAvaliableName());
                        }
                        getShortLink(shareUrl);
                    }
                });
            }
        }
        return convertView;
    }

    public void getShortLink(String url) {
        try {
            if (inviteFriendDialog == null) {
                inviteFriendDialog = new InviteFriendDialog(mContext, shareUrl, null, null);
            }
            Map param = new HashMap();
            param.put("url_long", url);
            param.put("source", "445798234");
            OkhttpManager.getInstance().loadDataByPost(ServerManager.URL_SHORT_LINK, param, new ICallBack() {
                @Override
                public void onSuccess(int statusCode, String result) {
                    LogUtil.e("yjl", "onSuccess short link：" + result);
                    try {
                        result = result.replaceAll(" ", "");
                        result = result.replaceAll("\\n", "");
                        List<InviteShortLinkEntity> inviteShortLinkEntity = ParseHelper.getModelList(result, "urls", InviteShortLinkEntity.class);
                        if (inviteShortLinkEntity != null && inviteShortLinkEntity.size() > 0) {
                            shareUrl = inviteShortLinkEntity.get(0).url_short;
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    inviteFriendDialog.setShareUrl(shareUrl);
                    ((BaseActivity) mContext).runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            inviteFriendDialog.show();
                        }
                    });

                }

                @Override
                public void onFail(int statusCode, String result) {
                    LogUtil.e("yjl", "onFail short link：" + result);
                    inviteFriendDialog.setShareUrl(commonShareUrl);
                    ((BaseActivity) mContext).runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            inviteFriendDialog.show();
                        }
                    });
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void clearData() {
        if (inviteFriendDialog != null) {
            inviteFriendDialog.dismiss();
            inviteFriendDialog = null;
        }
        addContactsFriendPresenter = null;
        mContext = null;
    }

    @Override
    public boolean isChildSelectable(int groupPosition, int childPosition) {
        return true;
    }


    /**
     * 初始化小组数据
     *
     * @return
     */
    private List<String> initGroup() {
        List<String> groupList = new ArrayList<>();
        for (MineFriendEntity friendEntity : friendEntities) {
            String group = friendEntity.sortKey.toUpperCase();
            if (!groupList.contains(group)) {
                groupList.add(group);
            }
        }
        Collections.sort(groupList);
        //索引排序，特殊排序排首位
        if (groupList.contains(FriendManager.FirstSort)) {
            groupList.remove(FriendManager.FirstSort);
            groupList.add(0, FriendManager.FirstSort);
        }
        return groupList;
    }

    /**
     * 分组联系人数据
     *
     * @param groupPos
     * @return
     */
    private List<MineFriendEntity> getChildFriend(int groupPos) {
        List<MineFriendEntity> entities = new ArrayList<>();
        String str = groupList.get(groupPos);
        for (MineFriendEntity friend : friendEntities) {
            if (str.equalsIgnoreCase(friend.sortKey)) {
                entities.add(friend);
            }
        }
        return entities;

    }

    private void initChildFriend() {
        childFriendEntity.clear();
        for (int i = 0; i < groupList.size(); i++) {
            List<MineFriendEntity> entities = getChildFriend(i);
            childFriendEntity.add(entities);
        }
    }

    /**
     * 分组viewholder
     */
    public class FriendGoupViewHolder {
        public TextView goup;
    }

    public class FriendViewHolder {
        public TextView nickeName; //别名
        public TextView friendFrom;//从哪来
        public TextView friendName;//姓名
        public CircleImageView friendImage;//好友头像
        public TextView text_friend_states;
        public RelativeLayout view_friend_phone;//背景view
    }


    /**
     * 顺序遍历所有元素．找到letter下的第一个item对应的position
     *
     * @param letter
     * @return
     */
    public int getFirstFriendPosition(String letter) {
        int size = friendEntities.size();
        for (int i = 0; i < size; i++) {
            if (letter.charAt(0) == friendEntities.get(i).sortKey.charAt(0)) {
                return i;
            }
        }
        return -1;
    }


    /**
     * 顺序遍历所有元素．找到position对应的title是什么（A,B,C?）然后找这个title下的第一个item对应的position
     *
     * @param position
     * @return
     */
    private int getFirstFriendPosition(int position) {

        String letter = friendEntities.get(position).contactsNumber;
        int cnAscii = ChineseToEnglish.getCnAscii(letter.toUpperCase().charAt(0));
        int size = friendEntities.size();
        for (int i = 0; i < size; i++) {
            if (cnAscii == friendEntities.get(i).sortKey.charAt(0)) {
                return i;
            }
        }
        return -1;
    }

    public void setFromViewName(String from) {
        this.from = from;
    }
}
